package com.ceic.hn.efiletransfer

import net.schmizz.sshj.SSHClient
import net.schmizz.sshj.transport.verification.PromiscuousVerifier
import org.slf4j.LoggerFactory
import java.io.File

class SSHChannel(private val sshClient: SSHClient) {

    fun write(file: File, outputPath: String) {
        sshClient.newSFTPClient().use {
            val dest = "${outputPath}/${file.name}"
            it.put(file.absolutePath, dest)
        }
    }

    fun close() {
        try {
            sshClient.close()
        } catch (ex: Exception) {
            logger.error("do destroy failed", ex)
        }
    }


    companion object {
        private val logger = LoggerFactory.getLogger(SSHChannel::class.java)

        fun create(channelSetting: ChannelSetting): SSHChannel {
            val sshClient = SSHClient().apply {
                addHostKeyVerifier(PromiscuousVerifier())
                connect(channelSetting.host, channelSetting.port)
                useCompression()
                authPassword(channelSetting.username, channelSetting.password)
            }
            return SSHChannel(sshClient)
        }

    }
}